#include "stdafx.h"
#include "ChessBoard.h"

HRESULT ChessBoard::Initialize()
{
    for (int index = 0; index < GC_CHESS_BOARD_ROW_COUNT; ++index)
    {
        for (int inner_index = 0; inner_index < GC_CHESS_BOARD_COL_COUNT; ++inner_index)
        {
            if (inner_index == 0 || inner_index == 1)
            {
                m_chess_board_fill.chess_board_fill[inner_index][index] = e_player_1;
            }
            else if (inner_index == GC_CHESS_BOARD_COL_COUNT - 1 ||
                inner_index == GC_CHESS_BOARD_COL_COUNT - 2)
            {
                m_chess_board_fill.chess_board_fill[inner_index][index] = e_player_2;
            }
            else
            {
                m_chess_board_fill.chess_board_fill[inner_index][index] = e_no_player;
            }

            RECT rect;
            rect.left = index * GC_CHESS_PIECE_WIDTH;
            rect.top = inner_index * GC_CHESS_PIECE_HEIGHT;
            rect.right = (index + 1) * GC_CHESS_PIECE_WIDTH;
            rect.bottom = (inner_index + 1) * GC_CHESS_PIECE_HEIGHT;
            m_chess_board_fill.chess_board_rect[inner_index][index] = rect;
        }
    }

    return S_OK;
}

HRESULT ChessBoard::SetPosFill(const CHESS_POS& chess_pos, const PLAYER& fill)
{
    m_chess_board_fill.chess_board_fill[chess_pos.row_index][chess_pos.col_index] = fill;

    return S_OK;
}

HRESULT ChessBoard::GetRectByChessPos(const CHESS_POS& chess_pos, RECT& rect)
{
    RETURN_AND_RECORD_ERROR_MESSAGE_IF_FALSE(
        chess_pos.row_index >= 0 || chess_pos.row_index < GC_CHESS_BOARD_ROW_COUNT)
    RETURN_AND_RECORD_ERROR_MESSAGE_IF_FALSE(
        chess_pos.col_index >= 0 || chess_pos.col_index < GC_CHESS_BOARD_COL_COUNT)

    rect = m_chess_board_fill.chess_board_rect[chess_pos.row_index][chess_pos.col_index];

    return S_OK;
}

HRESULT ChessBoard::GetChessFillByChessPos(const CHESS_POS& chess_pos, PLAYER& player)
{
    RETURN_AND_RECORD_ERROR_MESSAGE_IF_FALSE(
        chess_pos.row_index >= 0 || chess_pos.row_index < GC_CHESS_BOARD_ROW_COUNT)
    RETURN_AND_RECORD_ERROR_MESSAGE_IF_FALSE(
        chess_pos.col_index >= 0 || chess_pos.col_index < GC_CHESS_BOARD_COL_COUNT)

    player = m_chess_board_fill.chess_board_fill[chess_pos.row_index][chess_pos.col_index];

    return S_OK;
}

HRESULT ChessBoard::CheckPointInRect(const POINT& mouse, CHESS_POS& chess_pos)
{
    int index = 0;
    int inner_index = 0;
    BOOL is_in = FALSE;
    for (; index < GC_CHESS_BOARD_ROW_COUNT; ++index)
    {
        for (; inner_index < GC_CHESS_BOARD_COL_COUNT; ++inner_index)
        {
            is_in = PtInRect(&(m_chess_board_fill.chess_board_rect[index][inner_index]), mouse);
            if (is_in)
            {
                break;
            }
        }
        if (is_in)
        {
            break;
        }
        inner_index = 0;
    }

    chess_pos.row_index = index;
    chess_pos.col_index = inner_index;

    return S_OK;
}